package cn.stormling.note5.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;


/**
 * @author shuang.kou
 * @createTime 2020年05月14日 20:28:00
 */
public final class HelloNettyServer {

    private final int port;

    public HelloNettyServer(int port) {
        this.port = port;
    }

    /**
     * bossGroup 处理客户端Tcp请求                      老板 --- 接活 --- 线程为1
     * workerGroup 负责读写，交由对应的Handler处理        员工 --- 干活 --- 线程 cpu数*2
     *
     * @throws InterruptedException
     */
    private void start() throws InterruptedException {
        // 1.bossGroup 用于接收连接，workerGroup 用于具体的处理
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);// 老板
        EventLoopGroup workerGroup = new NioEventLoopGroup();       //   员工
        try {
            //2.创建服务端启动引导/辅助类：ServerBootstrap，引导我们进行服务端的启动工作
            ServerBootstrap b = new ServerBootstrap();
            //3.给引导类配置两大线程组,确定了线程模型
            b.group(bossGroup, workerGroup)
                    // (非必备)打印日志
//                    .handler(new LoggingHandler(LogLevel.INFO))
                    // 4.指定 IO 模型 ServerSocket 服务端
                    .channel(NioServerSocketChannel.class)
                    //指定了服务端消息的业务处理逻辑
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline p = ch.pipeline();
                            //5.可以自定义客户端消息的业务处理逻辑
                            p.addLast(new HelloServerHandler());
                        }
                    });
            // 6.绑定端口,调用 同步sync 方法阻塞知道绑定完成；bind()是异步的
            ChannelFuture f = b.bind(port).sync();
            // 7.阻塞等待直到服务器Channel关闭(closeFuture()方法获取Channel 的CloseFuture对象,然后调用sync()方法)
            f.channel().closeFuture().sync();
        } finally {
            //8.优雅关闭相关线程组资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new HelloNettyServer(8080).start();
    }

}
